﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier.utils;
using Cashier_Utils;
using Cashier_Service;
using Cashier_Model;
using System.Text.RegularExpressions;

namespace Cashier.purchase
{
    public partial class PurchaseGoodsInStockForm : Form
    {
        private MainForm mainform;
        private BillPurchaseService purchaseService;
        private BillPurchaseGoodsService purchaseGoodsService;
        private GoodsStorageService goodsStorageService;
        public delegate void SyncUpdateStorageResult(int numbers, int existNumber, int storageNumbers, DataGridViewRow row);

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        /// <param name="purchaseno">采购单号</param>
        public PurchaseGoodsInStockForm(MainForm mainform, String purchaseno)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.purchaseService = new BillPurchaseService();
            this.purchaseGoodsService = new BillPurchaseGoodsService();
            this.goodsStorageService = new GoodsStorageService();

            Button[] buttons = { button_query, button_storage };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);

            this.textbox_purchaseno.Text = purchaseno;
            this.GenerateDataGridViewColumns();
            this.DataGridViewBindData();
        }

        #region 功能方法实现

        /// <summary>
        /// 生成DataGridView列
        /// </summary>
        private void GenerateDataGridViewColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("barcode", "商品条码", true, 15, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("category_name", "分类", true, 11, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_name", "名称", true, 21, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_norm", "规格", true, 11, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_cost", "进货单价", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount", "折扣率", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_disc", "折后单价", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "进货数量", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("storage_number", "入库数量", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetEmptyDataGridViewColumn("结果", true, 7, ActKey.LEFT, ActKey.LEFT, true));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_id", null, true, 0, null, null, false, false));
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        public void DataGridViewBindData()
        {
            try
            {
                dataGridView1.DataSource = null;
                String purchaseno = textbox_purchaseno.Text.Trim();
                if (!String.IsNullOrEmpty(purchaseno))
                {
                    BillPurchase purchase = this.purchaseService.GetBillPurchase(0, purchaseno);
                    if (purchase != null)
                    {
                        label_purchaseUser.Text = purchase.AdminName;
                        label_purchaseDate.Text = purchase.PurchaseDate.ToString("yyyy-MM-dd");

                        DataTable dt = this.purchaseGoodsService.GetPurchaseGoodsStorageTable(purchaseno);
                        this.dataGridView1.DataSource = dt;
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            dataGridView1.Rows[0].Selected = true;
                        }
                        dataGridView1.Columns[0].Visible = false;
                    }
                    else
                    {
                        MessageBox.Show("商品采购单不存在！");
                    }
                }             
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 商品入库
        /// </summary>
        private void GoodsStorage()
        {
            int count = 0;
            String enterpriseNo = mainform.Admin.EnterpriseNo;
            String storeNo = mainform.Admin.StoreNo;
            String adminUsername = mainform.Admin.Username;
            String adminName = mainform.Admin.Name;
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                int numbers = Int32.Parse(row.Cells["numbers"].Value.ToString());
                int existNumber = 0;
                int storageNumber = 0;
                String reg = "^(0|[1-9][0-9]*)$";
                Object obj = row.Cells["storage_number"].Value;
                if (obj != null && Regex.IsMatch(obj.ToString(), reg))
                {
                    existNumber = Int32.Parse(obj.ToString());
                }

                if (numbers > existNumber)
                {
                    GoodsStorage storage = new GoodsStorage();
                    storage.EnterpriseNo = enterpriseNo;
                    storage.StoreNo = storeNo;
                    storage.PurchaseNo = textbox_purchaseno.Text.Trim();
                    storage.GoodsId = (long)row.Cells["goods_id"].Value;
                    storage.Barcode = row.Cells["barcode"].Value.ToString();
                    storage.CategoryName = row.Cells["category_name"].Value.ToString();
                    storage.GoodsName = row.Cells["goods_name"].Value.ToString();
                    storage.GoodsNorm = row.Cells["goods_norm"].Value.ToString();
                    storage.PriceCost = Decimal.Parse(row.Cells["price_cost"].Value.ToString());
                    storage.Discount = Decimal.Parse(row.Cells["discount"].Value.ToString());
                    storage.PriceDisc = Decimal.Parse(row.Cells["price_disc"].Value.ToString());
                    storage.Numbers = numbers;
                    storage.StorageNumber = numbers - existNumber;
                    storage.AdminUsername = adminUsername;
                    storage.AdminName = adminName;
                    storage.StorageDate = DateTime.Now;
                    long id = goodsStorageService.InsertGoodsStorage(storage);
                    if (id > 0)
                    {
                        storageNumber = storage.StorageNumber;
                        count++;
                    }
                }
                Object[] objArr = { numbers, existNumber, storageNumber, row };
                BeginInvoke(new SyncUpdateStorageResult(UpdateStorageResult), objArr);
            }
            if (count > 0)
                MessageBox.Show("入库成功！");
            else
                MessageBox.Show("无商品入库！");
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.DataGridViewBindData();
        }

        /// <summary>
        /// 商品入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_storage_Click(object sender, EventArgs e)
        {
            this.DataGridViewBindData();
            this.GoodsStorage();
        }

        #endregion


        #region  异步更新界面信息

        /// <summary>
        /// 更新商品入库数量
        /// </summary>
        /// <param name="numbers">采购数量</param>
        /// <param name="existNumber">已导入的数量</param>
        /// <param name="storageNumbers">当前导入的数量</param>
        /// <param name="row">数据行</param>
        protected void UpdateStorageResult(int numbers, int existNumber, int storageNumbers, DataGridViewRow row)
        {
            if (storageNumbers > 0)
            {
                row.Cells["storage_number"].Value = storageNumbers.ToString();
                row.Cells[row.Cells.Count - 2].Style.ForeColor = Color.Red;
                row.Cells[row.Cells.Count - 2].Value = "成功";
            }
        }

        #endregion

    }
}
